package com.zbkj.crmeb.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.github.pagehelper.PageHelper;

import com.utils.CrmebUtil;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderStatus;
import com.zbkj.crmeb.store.request.RetailShopRequest;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.service.RetailShopService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.service.StoreOrderStatusService;
import com.zbkj.crmeb.system.model.SystemGroupData;
import com.zbkj.crmeb.system.dao.SystemGroupDataDao;
import com.zbkj.crmeb.system.request.SystemFormItemCheckRequest;
import com.zbkj.crmeb.system.request.SystemGroupDataRequest;
import com.zbkj.crmeb.system.request.SystemGroupDataSearchRequest;
import com.zbkj.crmeb.system.service.SystemAttachmentService;
import com.zbkj.crmeb.system.service.SystemFormTempService;
import com.zbkj.crmeb.system.service.SystemGroupDataService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
* @author Mr.Zhang
* @description SystemGroupDataServiceImpl 接口实现
* @date 2020-05-15
*/
@Service
public class SystemGroupDataServiceImpl extends ServiceImpl<SystemGroupDataDao, SystemGroupData> implements SystemGroupDataService {

    @Resource
    private SystemGroupDataDao dao;

    @Autowired
    private SystemFormTempService systemFormTempService;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private RetailShopService retailShopService;

    @Autowired
    private StoreOrderStatusService storeOrderStatusService;

    @Autowired
    private UserService userService;

    /**
    * 列表
    * @param request 请求参数
    * @param pageParamRequest 分页类参数
    * @author Mr.Zhang
    * @since 2020-05-15
    * @return List<SystemGroupData>
    */
    @Override
    public List<SystemGroupData> getList(SystemGroupDataSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 SystemGroupData 类的多条件查询
        LambdaQueryWrapper<SystemGroupData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        SystemGroupData model = new SystemGroupData();
        BeanUtils.copyProperties(request, model, "keywords");
        if (StringUtils.isNotBlank(request.getKeywords())) {
            lambdaQueryWrapper.like(SystemGroupData::getKeywords, request.getKeywords());
        }
        lambdaQueryWrapper.setEntity(model);
        if (Objects.equals(request.getGid(), Constants.GROUP_DATA_ID_INDEX_KEYWORDS)) {
            lambdaQueryWrapper.orderByDesc(SystemGroupData::getSort).orderByAsc(SystemGroupData::getId);
        } else {
            lambdaQueryWrapper.orderByAsc(SystemGroupData::getSort).orderByAsc(SystemGroupData::getId);
        }
        return dao.selectList(lambdaQueryWrapper);
    }

    /**
     * 保存数据
     * @param systemGroupDataRequest SystemGroupDataRequest 数据保存
     * @author Mr.Zhang
     * @since 2020-04-13
     * @return bool
     */
    @Override
    public boolean create(SystemGroupDataRequest systemGroupDataRequest) {
        //检测form表单，并且返回需要添加的数据
        systemFormTempService.checkForm(systemGroupDataRequest.getForm());

        SystemGroupData systemGroupData = new SystemGroupData();
        systemGroupData.setGid(systemGroupDataRequest.getGid());

        String value = JSONObject.toJSONString(systemGroupDataRequest.getForm());
        value = systemAttachmentService.clearPrefix(value);

        systemGroupData.setValue(value);

//        int sort = 0;
//        for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemGroupDataRequest.getForm().getFields()) {
//            if(systemFormItemCheckRequest.getName().equals("sort")){
//                sort = Integer.parseInt(systemFormItemCheckRequest.getName());
//                break;
//            }
//        }
        systemGroupData.setSort(systemGroupDataRequest.getForm().getSort());
        systemGroupData.setStatus(systemGroupDataRequest.getForm().getStatus());
        systemGroupData.setMerId(systemGroupDataRequest.getForm().getMerId());
        return save(systemGroupData);
    }

    /**
     * 修改组合数据详情表
     * @param id integer id
     * @param request 修改参数
     * @author Mr.Zhang
     * @since 2020-05-15
     * @return bool
     */
    @Override
    public boolean update(Integer id, SystemGroupDataRequest request) {
        //检测form表单，并且返回需要添加的数据
        systemFormTempService.checkForm(request.getForm());

        SystemGroupData systemGroupData = new SystemGroupData();
        systemGroupData.setId(id);
        systemGroupData.setGid(request.getGid());

        String value = JSONObject.toJSONString(request.getForm());
        value = systemAttachmentService.clearPrefix(value);
        systemGroupData.setValue(value);

        systemGroupData.setSort(request.getForm().getSort());
        systemGroupData.setStatus(request.getForm().getStatus());
        systemGroupData.setMerId(request.getForm().getMerId());
        return updateById(systemGroupData);
    }

    /**
     * 通过gid获取列表 推荐二开使用
     * @param gid Integer group id
     * @author Mr.Zhang
     * @since 2020-05-15
     * @return List<T>
     */
    @Override
    public <T> List<T> getListByGid(Integer gid, Class<T> cls) {
        SystemGroupDataSearchRequest systemGroupDataSearchRequest = new SystemGroupDataSearchRequest();
        systemGroupDataSearchRequest.setGid(gid);
        systemGroupDataSearchRequest.setStatus(true);
        List<SystemGroupData> list = getList(systemGroupDataSearchRequest, new PageParamRequest());

        List<T> arrayList = new ArrayList<>();
        if(list.size() < 1){
            return null;
        }

        for (SystemGroupData systemGroupData : list) {
            JSONObject jsonObject = JSONObject.parseObject(systemGroupData.getValue());
            List<SystemFormItemCheckRequest> systemFormItemCheckRequestList = CrmebUtil.jsonToListClass(jsonObject.getString("fields"), SystemFormItemCheckRequest.class);
            if(systemFormItemCheckRequestList.size() < 1){
                continue;
            }
            HashMap<String, Object> map = new HashMap<>();
            T t;
            for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemFormItemCheckRequestList) {
                map.put(systemFormItemCheckRequest.getName(), systemFormItemCheckRequest.getValue());
            }
            map.put("id", systemGroupData.getId());
            map.put("merId", systemGroupData.getMerId());
            t = CrmebUtil.mapToObj(map, cls);
            arrayList.add(t);
        }

        return arrayList;
    }

    /**
      * 通过gid获取列表
      * @param gid Integer group id
      * @author Mr.Zhang
      * @since 2020-05-15
      * @return List<HashMap<String, Object>>
      */
    @Override
    public List<HashMap<String, Object>> getListMapByGid(Integer gid, Integer merId) {
        SystemGroupDataSearchRequest systemGroupDataSearchRequest = new SystemGroupDataSearchRequest();
        systemGroupDataSearchRequest.setGid(gid);
        systemGroupDataSearchRequest.setStatus(true);
        if (Objects.nonNull(merId)) {
            systemGroupDataSearchRequest.setMerId(merId);
        }
        List<SystemGroupData> list = getList(systemGroupDataSearchRequest, new PageParamRequest());

        List<HashMap<String, Object>> arrayList = new ArrayList<>();
        if(list.size() < 1){
            return null;
        }

        for (SystemGroupData systemGroupData : list) {
            JSONObject jsonObject = JSONObject.parseObject(systemGroupData.getValue());
            List<SystemFormItemCheckRequest> systemFormItemCheckRequestList = CrmebUtil.jsonToListClass(jsonObject.getString("fields"), SystemFormItemCheckRequest.class);
            if(systemFormItemCheckRequestList.size() < 1){
                continue;
            }
            HashMap<String, Object> map = new HashMap<>();

            //我的推广-根据分销配置
            if (systemFormItemCheckRequestList.get(0).getValue().equals("我的推广")){
                if (retailFlag()){
                    systemFormItemMap(map, systemFormItemCheckRequestList);
                }
            }else{
                systemFormItemMap(map, systemFormItemCheckRequestList);
            }

            map.put("id", systemGroupData.getId());
            arrayList.add(map);
        }

        return arrayList;
    }

    private void systemFormItemMap(HashMap<String, Object> map, List<SystemFormItemCheckRequest> systemFormItemCheckRequestList) {
        for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemFormItemCheckRequestList) {
            map.put(systemFormItemCheckRequest.getName(), systemFormItemCheckRequest.getValue());
        }
    }

    /**
     * 分销配置
     */
    private Boolean retailFlag() {
            //获取分销配置
            RetailShopRequest retailShop = retailShopService.getManageInfo();
            //分销启用
            String brokerageFuncStatus = retailShop.getBrokerageFuncStatus();
            //分销模式
            String storeBrokerageStatus = retailShop.getStoreBrokerageStatus();
            //满额分销最低金额
            String storeBrokeragePrice = retailShop.getStoreBrokeragePrice();
            if ("1".equals(brokerageFuncStatus)) {
                switch (storeBrokerageStatus) {
                    //指定分销
                    case "1":
                        User user = userService.getInfo();
                        if (ObjectUtils.isNotNull(user)){
                            Boolean isPromoter = user.getIsPromoter();
                            return isPromoter;
                        }
                        return false;
                    //人人分销
                    case "2":
                        return true;
                    //满额分销
                    case "3":
                        StoreOrderSearchRequest storeOrderSearchRequest = new StoreOrderSearchRequest();
                        storeOrderSearchRequest.setUid(userService.getUserIdException());
                        QueryWrapper<StoreOrder> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(StoreOrder::getPaid,1);
                        queryWrapper.lambda().eq(StoreOrder::getIsDel,0);

                        //支付成功且未退款
                        LambdaQueryWrapper<StoreOrderStatus> payQueryWrapper = new LambdaQueryWrapper<>();
                        payQueryWrapper.select(StoreOrderStatus::getOid);
                        payQueryWrapper.eq(StoreOrderStatus::getChangeType, Constants.ORDER_LOG_PAY_SUCCESS);
                        payQueryWrapper.ne(StoreOrderStatus::getChangeType, Constants.ORDER_LOG_REFUND_PRICE);
                        payQueryWrapper.groupBy(StoreOrderStatus::getOid);
                        List<StoreOrderStatus> storeOrderStatusList = storeOrderStatusService.list(payQueryWrapper);
                        List<Integer> oidList = new ArrayList<>();
                        if (CollectionUtils.isNotEmpty(storeOrderStatusList)) {
                            storeOrderStatusList.stream().forEach((storeOrderStatus) -> {
                                if (null != storeOrderStatus.getOid()) {
                                    oidList.add(storeOrderStatus.getOid());
                                }
                            });
                            queryWrapper.in("id", oidList);
                        }

                        List<StoreOrder> storeOrderList = storeOrderService.list(queryWrapper);
                        if (CollectionUtils.isEmpty(storeOrderList)){
                            return false;
                        }
                        for (StoreOrder storeOrder: storeOrderList){
                            if (storeOrder.getPayPrice().compareTo(new BigDecimal(storeBrokeragePrice)) == 1){
                                return true;
                            }
                        }
                }
            }
        return false;
    }

    /**
     * 通过gid获取列表
     * @param groupDataId Integer group id
     * @author Mr.Zhang
     * @since 2020-05-15
     * @return <T>>
     */
    public <T> T getNormalInfo(Integer groupDataId, Class<T> cls){
        SystemGroupData systemGroupData = getById(groupDataId);
        if(null == systemGroupData || !systemGroupData.getStatus()){
            return null;
        }

        JSONObject jsonObject = JSONObject.parseObject(systemGroupData.getValue());
        List<SystemFormItemCheckRequest> systemFormItemCheckRequestList = CrmebUtil.jsonToListClass(jsonObject.getString("fields"), SystemFormItemCheckRequest.class);
        if(systemFormItemCheckRequestList.size() < 1){
            return null;
        }
        HashMap<String, Object> map = new HashMap<>();
        T t;
        for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemFormItemCheckRequestList) {
            map.put(systemFormItemCheckRequest.getName(), systemFormItemCheckRequest.getValue());
        }
        map.put("id", systemGroupData.getId());
        t = CrmebUtil.mapToObj(map, cls);

        return t;
    }

    @Override
    public <T> List<T> getListByGid(Integer gid, Class<T> cls, Integer merId) {
        SystemGroupDataSearchRequest systemGroupDataSearchRequest = new SystemGroupDataSearchRequest();
        systemGroupDataSearchRequest.setGid(gid);
        systemGroupDataSearchRequest.setStatus(true);
        systemGroupDataSearchRequest.setMerId(merId);
        List<SystemGroupData> list = getList(systemGroupDataSearchRequest, new PageParamRequest());

        List<T> arrayList = new ArrayList<>();
        if(list.size() < 1){
            return null;
        }

        for (SystemGroupData systemGroupData : list) {
            JSONObject jsonObject = JSONObject.parseObject(systemGroupData.getValue());
            List<SystemFormItemCheckRequest> systemFormItemCheckRequestList = CrmebUtil.jsonToListClass(jsonObject.getString("fields"), SystemFormItemCheckRequest.class);
            if(systemFormItemCheckRequestList.size() < 1){
                continue;
            }
            HashMap<String, Object> map = new HashMap<>();
            T t;
            for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemFormItemCheckRequestList) {
                map.put(systemFormItemCheckRequest.getName(), systemFormItemCheckRequest.getValue());
            }
            map.put("id", systemGroupData.getId());
            t = CrmebUtil.mapToObj(map, cls);
            arrayList.add(t);
        }

        return arrayList;
    }

    @Override
    public Boolean updateStatus(Integer id, Boolean status) {
        return this.update(Wrappers.<SystemGroupData>lambdaUpdate()
                .eq(SystemGroupData::getId, id)
                .set(SystemGroupData::getStatus, status));
    }

}

